/**
 * @file tdsBsp.c
 * @author  xiaowine (xiaowine@sina.cn)
 * @brief
 * @version 01.00
 * @date    2022-03-11
 *
 * @copyright Copyright (c) {2020}  xiaowine
 *
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2022-03-11 <td>1.0     <td>wangh     <td>内容
 * </table>
 * ******************************************************************
 * *                   .::::
 * *                 .::::::::
 * *                ::::::::::
 * *             ..:::::::::::
 * *          '::::::::::::
 * *            .:::::::::
 * *       '::::::::::::::..        女神助攻,流量冲天
 * *            ..::::::::::::.     永不宕机,代码无bug
 * *          ``:::::::::::::::
 * *           ::::``:::::::::'        .:::
 * *          ::::'   ':::::'       .::::::::
 * *        .::::'      ::::     .:::::::'::::
 * *       .:::'       :::::  .:::::::::' ':::::
 * *      .::'        :::::.:::::::::'      ':::::
 * *     .::'         ::::::::::::::'         ``::::
 * * ...:::           ::::::::::::'              ``::
 * *```` ':.          ':::::::::'                  ::::.
 * *                   '.:::::'                    ':'````.
 * ******************************************************************
 */

/* Private includes ----------------------------------------------------------*/
#include "tdsBsp.h"
#include <string.h>
#include "stdio.h"
#include "stm32g0xx_hal.h"
#include "tm1640.h"
#include "usart.h"
#include "user_data.h"
/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
static uint8_t  u8FrameCheckSum;
static uint8_t  u8FrameDataLength;
uint8_t         g_ComBuff[PROTOCOL_FRAME_MaxLen];
PROTOCOL_STATUS g_ComStat;  //通讯通道工作状态
// uint8_t g_ComGap[1];          //通讯帧接收间隔定时器
ProtocolLayer    Protocol;
volatile uint8_t uart2RXBuff;

uint16_t tds0 = 0;
uint16_t tds1 = 0;
/* Private function prototypes -----------------------------------------------*/
static uint8_t tdsxPortSerialGetByte(char *pucByte, uint8_t ucMB_Number);
static void    tdsUsartVarInit(void);
static void    tdsUsart2InitConf(void);
/* Private user code ---------------------------------------------------------*/

///*************************************************
// Function:void Comm_Service(void)// 函数名称
// Description:// 函数功能、性能等的描述
//			执行通讯任务
//			状态机转换（正常情况）: RECV_Wait->RECV_Going->RECV_Over->
//                                     SEND_Wait->SEND_Going->SEND_Over->RECV_Wait
// Author:xdp（作者）
// Calls:// 被本函数调用的函数清单
// Called By:// 调用本函数的函数清单
//			main();
// Input:// 输入参数说明，包括每个参数的作
//     // 用、取值说明及参数间关系。
// Output:// 对输出参数的说明。
// Return:// 函数返回值的说明
// Others:// 其它说明
//*************************************************/
void tdsComService(void)
{
    uint8_t i     = 0;
    uint8_t u8Sum = 0x00;
    if (g_ComStat == RECV_Over) {
        for (i = 0; i < TDS_SEND_NUM - 1; i++) {
            u8Sum += g_ComBuff[i];
        }
        if (u8Sum == g_ComBuff[TDS_SEND_NUM - 1]) {
            tds0 = g_ComBuff[1] << 8 | g_ComBuff[2];
            tds1 = g_ComBuff[3] << 8 | g_ComBuff[4];
            if (tds0 > 999) {
                tds0 = 999;
            }
            if (tds1 > 999) {
                tds1 = 999;
            }
            printf("tds:%d %d|temp:%d %d\r\n", tds0, tds1, g_ComBuff[7] << 8 | g_ComBuff[8], g_ComBuff[9] << 8 | g_ComBuff[10]);
            uint16_t tds00 = tds0;
            uint16_t tds01 = tds1;
            for (char i = 0; i < 3; i++) {
                if (!SEGMENT_TDS0) {
                    segmentValue[4 + i] = ch_table[tds00 % 10];
                    tds00 /= 10;
                }
                if (!SEGMENT_TDS1) {
                    segmentValue[9 - i] = ch_table[tds01 % 10];
                    tds01 /= 10;
                }
            }
        }
        memset(&g_ComBuff[0], 0x00, PROTOCOL_FRAME_MaxLen);
        g_ComStat = SEND_Wait;
    }
    return;
}

// TDS串口接收数据
uint8_t tdsPortSerialReceiveFSM(void)
{
    uint8_t RXDByte;
    /* Always read the character. */
    (void)tdsxPortSerialGetByte((char *)&RXDByte, 0);
    switch (Protocol.StatckStatus) {
        case PROTOCOL_STACK_IDLE:  // 空闲状态,等待接收帧首字符(01)
            if (0xAA == RXDByte) {
                g_ComStat             = RECV_Going;  //置"接收进行"状态
                g_ComBuff[0]          = RXDByte;
                u8FrameCheckSum       = RXDByte;
                Protocol.DataCount    = 1;
                u8FrameDataLength     = 11;
                Protocol.StatckStatus = PROTOCOL_STACK_RCV;
            }
            break;
        case PROTOCOL_STACK_CK:
            break;
        case PROTOCOL_STACK_RCV:
            // 累加校验和
            u8FrameCheckSum += RXDByte;
            g_ComBuff[(Protocol.DataCount)++] = RXDByte;
            u8FrameDataLength--;
            // 接收数据域的数据
            if (!u8FrameDataLength) {
                // 接收校验和
                Protocol.StatckStatus = PROTOCOL_STACK_IDLE;
                g_ComStat             = RECV_Over;  //置"接收完成"状态
            }
            break;
        case PROTOCOL_STACK_CS:
            g_ComBuff[(Protocol.DataCount)++] = RXDByte;
            u8FrameCheckSum += RXDByte;
            u8FrameDataLength--;
            // 接收数据域的数据
            if (!u8FrameDataLength) {
            }
            break;
        case PROTOCOL_STACK_END:

            break;
        default:
            Protocol.StatckStatus = PROTOCOL_STACK_IDLE;
            g_ComStat             = INIT_Apply;  //置"初始化"状态
            break;
    }
    HAL_UART_Receive_IT(&huart2, (uint8_t *)&uart2RXBuff, 1);
    return 1;
}

static uint8_t tdsxPortSerialGetByte(char *pucByte, uint8_t ucMB_Number)
{
    *pucByte = uart2RXBuff;
    return 1;
}

//串口发送数据
uint8_t tdsSend(void)
{
    uint8_t u8SendBuf[TDS_SEND_NUM] = {0};
    uint8_t u8Head                  = 0xA0;
    uint8_t u8Sum                   = 0x00;
    uint8_t i;

    // if(g_ComStat == SEND_Wait)
    {
        u8SendBuf[0] = u8Head;
        u8SendBuf[1] = 0x00;
        u8SendBuf[2] = 0x00;
        u8SendBuf[3] = 0x00;
        u8SendBuf[4] = 0x00;
        for (i = 0; i < TDS_SEND_NUM - 1; i++) {
            u8Sum += u8SendBuf[i];
        }
        u8SendBuf[TDS_SEND_NUM - 1] = u8Sum;

        if (HAL_UART_Transmit_DMA(&huart2, u8SendBuf, TDS_SEND_NUM) != HAL_OK) {
            u8Sum = 0;
        } else {
            u8Sum = 1;
        }
        g_ComStat = SEND_Going;
    }
    return u8Sum;
}

//通信串口初始化
void tdsUsartInit(void)
{
    tdsUsartVarInit();
    tdsUsart2InitConf();
}
static void tdsUsartVarInit(void)
{
    g_ComStat = INIT_Apply;
    //    g_ComGap[0] = 0;
    Protocol.StatckStatus = PROTOCOL_STACK_IDLE;
    memset(&g_ComBuff[0], 0x00, PROTOCOL_FRAME_MaxLen);
    return;
}
static void tdsUsart2InitConf(void)
{
    __HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
    HAL_UART_Receive_IT(&huart2, (uint8_t *)&uart2RXBuff, 1);
    return;
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    /* Prevent unused argument(s) compilation warning */
    UNUSED(huart);
    if (huart == &huart2) {
        tdsPortSerialReceiveFSM();
    }
    /* NOTE : This function should not be modified, when the callback is needed,
            the HAL_UART_RxCpltCallback can be implemented in the user file.
   */
}
